import * as echarts from "echarts";

const initChart = (id, chart, seriesDatas, xAxisData) => {
  const chartDom = document.getElementById(id);
  if (chart) chart.clear();
  chart = echarts.init(chartDom);

  const option = {
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    legend: {
      data: seriesDatas.map((item) => item.name),
      selectedMode: true,
      selected: seriesDatas.reduce((acc, item) => {
        acc[item.name] = true;
        return acc;
      }, {}),
      icon: "circle",
      itemWidth: 12,
      itemHeight: 12,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: xAxisData,
    },
    yAxis: {
      type: "value",
      axisLine: {
        show: true,
        lineStyle: {
          color: "#999999",
        },
      },
    },
    series: seriesDatas.map((item) => ({
      name: item.name,
      type: "line",
      smooth: true,
      data: item.data,
      itemStyle: {
        color: `rgba(${item.rgb},1)`,
      },
      areaStyle: {
        color: {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: `rgba(${item.rgb},0.9)`,
            },
            {
              offset: 1,
              color: `rgba(${item.rgb},0.9)`,
            },
          ],
        },
      },
    })),
  };

  option && chart.setOption(option);
};

export default initChart;
